package controller

import (
	"pro-downloader/app/ichan"
	"pro-downloader/app/model"
	"pro-downloader/app/utils"
	"fmt"
	"github.com/gin-gonic/gin"
	"gopkg.in/go-playground/validator.v8"
	"net/http"
)

func TaskAddShow(context *gin.Context) {
	context.HTML(http.StatusOK, "task_add.html", gin.H{})
}

func TaskAdd(context *gin.Context) {
	task := model.Task{}
	taskDb := model.TaskDB{}

	if err := context.ShouldBind(&task); err != nil {
		context.JSON(http.StatusOK, gin.H{"code": 10, "msg": task.GetError(err.(validator.ValidationErrors))})
		return
	}
	//log.Printf("接收到: %v\n", task)

	taskDb.Url = task.Url
	taskDb.Name = task.Name
	taskDb.Status = "10"
	res, err := utils.DbConn.Exec("insert into task(name,url,status) values (?,?,?)", taskDb.Name, taskDb.Url, taskDb.Status)
	if err != nil {
		fmt.Println("exec failed, ", err)
		return
	}
	id, err := res.LastInsertId()
	if err != nil {
		fmt.Println("exec failed, ", err)
		return
	}
	savePath := utils.GetDownloadPath()+task.Name
	//开启一个线程下载
	go utils.DownloadFile(task.Url, savePath, func(fileTotalSize, hasDownloadSize int64,  isFinish bool) {
		if isFinish {
			model.UpdateTask(id,30)
		}
		//log.Printf("下载信息 total:%v => %v", fileTotalSize, hasDownloadSize)
		ichan.GetDownloadInfoChan() <- &model.DownLoadInfo{id, fileTotalSize, hasDownloadSize, isFinish}
	})

	context.JSON(http.StatusOK, gin.H{"code": 0, "msg": "添加"+string(id)+"成功!!!"})
}

func Test(context *gin.Context) {

	//url := "http://220.112.193.201/files/114200000632A1B7/down.pggho.com/Ghost_XP_IE8_CJ_V2017.05.iso"
	//savefile := "./download/test"+utils.RandNum(5)+".iso"

	url := "https://desk-fd.zol-img.com.cn/t_s4096x2160c5/g2/M00/0A/0C/ChMlWl1UvBGIPMUQADWkWWYO9DcAAMkeAMR56YANaRx249.jpg"
	savefile := utils.GetDownloadPath()+utils.RandNum(8)+".jpg"

	//开启一个线程下载
	go utils.DownloadFile(url, savefile, func(fileTotalSize, hasDownloadSize int64, isFinish bool) {
		if isFinish {
			fmt.Println("更新状态:30")
			model.UpdateTask(39,30)
		}
		//log.Printf("下载信息 total:%v => %v", fileTotalSize, hasDownloadSize)
		ichan.GetDownloadInfoChan() <- &model.DownLoadInfo{39, fileTotalSize, hasDownloadSize, isFinish}
	})
	context.JSON(http.StatusOK, gin.H{"code": 0, "msg": "添加成功!!!"})
}

func TaskList(context *gin.Context) {
	taskDb := []model.TaskDB{}
	err := utils.DbConn.Select(&taskDb, "select id, name, url,status from task order by id DESC")
	if err != nil {
		fmt.Println("exec failed, ", err)
		return
	}
	context.JSON(http.StatusOK, gin.H{"code": "0", "msg": "success", "count": 13, "data": taskDb})
}

func TaskDel(ctx *gin.Context)  {
	id := ctx.Param("id")
	if !utils.IsNum(id){
		ctx.JSON(http.StatusOK, gin.H{"code": "10", "msg": "未接收到参数"})
		return
	}

	res, err := utils.DbConn.Exec("delete from task where id=?", id)
	if err != nil {
		fmt.Println("执行sql失败, ", err)
		return
	}
	row, err := res.RowsAffected()
	if err != nil {
		fmt.Println("UpdateTask failed, ", err)
	}
	//fmt.Println("更新",row,"状态:30")
	if row == 0 {
		ctx.JSON(http.StatusOK, gin.H{"code": "10", "msg": "删除失败"})
		return
	}
	ctx.JSON(http.StatusOK, gin.H{"code": "0", "msg": "删除成功!!"})
}